package com.bwie.service.Impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.pojo.Menu;
import com.bwie.pojo.Role;
import com.bwie.utils.R;
import com.bwie.vo.LoginFrom;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TUser;
import com.bwie.mapper.TUserMapper;
import com.bwie.service.TUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService{
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Override
    public R login(LoginFrom loginFrom) {
        LambdaQueryWrapper<TUser> tUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        TUser tUser = tUserMapper.selectOne(
                tUserLambdaQueryWrapper.eq(TUser::getUserName, loginFrom.getUserName())
        );
        if(ObjectUtils.isEmpty(tUser)){
            return R.ERROR(500,"账号未注册");
        }
        if(!tUser.getPassword().equalsIgnoreCase(loginFrom.getPassword())){
            return R.ERROR(500,"密码错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("id", tUser.getId()).compact();
        String tokenKey = "token-"+tUser.getId();
        redisTemplate.opsForValue().set(tokenKey,token,15, TimeUnit.MINUTES);
        tUser.setToken(token);
        tUser.setPassword(null);
        return R.OK(tUser);
    }

    @Override
    public R UseList(PageInfoVo pageInfoVo) {
        Page<TUser> tUserPage = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        QueryWrapper<TUser> tUserQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<TUser> tUserLambdaQueryWrapper = tUserQueryWrapper.lambda().orderByDesc(TUser::getCreateTime);
        Page<TUser> tUserPage1 = tUserMapper.selectPage(tUserPage, tUserLambdaQueryWrapper);
        return R.OK(tUserPage1);
    }

    @Override
    public R addLogin(TUser tUser) {
        TUser tUser1 = tUserMapper.selectOne(
                new QueryWrapper<TUser>().lambda().eq(TUser::getUserName, tUser.getUserName())
        );
        if(ObjectUtils.isNotEmpty(tUser1)){
            return R.ERROR(500,"用户已存在");
        }
        tUser.setCreateTime(new Date());
        tUserMapper.insert(tUser);
        return R.OK();
    }

    @Override
    public R getUser() {
        String token = httpServletRequest.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        TUser tUser = tUserMapper.selectById(id);
        return R.OK(tUser);
    }

    @Override
    public R getUserRole() {
        String token = httpServletRequest.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        List<Role> roleList = tUserMapper.getUserRole(id);
        return R.OK(roleList);
    }

    @Override
    public R getTreeList() {
        String token = httpServletRequest.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return R.ERROR(500,"请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        List<Menu> treeList = tUserMapper.getTreeList(id);

        List<Tree<String>> build = TreeUtil.build(treeList, "0", (menu, tree) -> {
            tree.setId(menu.getId().toString());
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid().toString());
            tree.putExtra("path",menu.getMenuPath());
        });
        return R.OK();
    }

    @Override
    public R getUserById(Integer id) {
        TUser tUser = tUserMapper.selectById(id);
        if(ObjectUtils.isEmpty(tUser)){
            return R.ERROR(500,"用户不存在");
        }
        return R.OK(tUser);
    }
}
